package com.lnlyj.media.ui;

import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.lnlyj.media.R;
import com.lnlyj.media.base.BaseAdapter;
import com.lnlyj.media.data.MediaItem;

import java.util.Objects;

import androidx.annotation.NonNull;

/**
 * wanglei 2020-04-21
 */
public class PreviewAdapter extends BaseAdapter<MediaItem, PreviewHolder> {

    private MediaItem currentItem;

    private boolean isSuper;

    public PreviewAdapter(boolean isSuper) {
        this.isSuper = isSuper;
    }

    @Override
    public PreviewHolder getViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PreviewHolder(View.inflate(parent.getContext(), R.layout.item_preview, null));
    }

    @Override
    public void bindData(PreviewHolder holder, int position) {
        MediaItem item = getItem(position);
        Glide.with(holder.imageView.getContext()).load(item.getUri()).skipMemoryCache(false).crossFade(0).into(holder.imageView);
        if (Objects.equals(item, currentItem)) {
            holder.selectView.setVisibility(View.VISIBLE);
        } else {
            holder.selectView.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(view -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(item, position);
            }
        });

        if (SelectionManager.getInstance().contains(item)) {
            holder.tipView.setVisibility(View.GONE);
        } else {
            holder.tipView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        if (isSuper) {
            return super.getItemCount();
        }
        return SelectionManager.getInstance().getMediaItems().size();
    }

    @Override
    public MediaItem getItem(int position) {
        if (isSuper) {
            return super.getItem(position);
        }
        return SelectionManager.getInstance().getMediaItems().get(position);
    }

    public void setCurrentItem(MediaItem currentItem) {
        this.currentItem = currentItem;
        notifyDataSetChanged();
    }
}
